package crazyboyfeng.autodroid.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import crazyboyfeng.autodroid.R;
import crazyboyfeng.autodroid.action.TaskTypeAction;
import crazyboyfeng.autodroid.bean.TaskBean;
import crazyboyfeng.autodroid.db.DBManager;
import crazyboyfeng.autodroid.ui.MainActivity;


public class TaskService extends Service {

		NotificationManager mNM;
		TaskTypeAction action = new TaskTypeAction();
		private static final String TAG = "TaskService";  

	    @Override 
	    public void onStart(Intent intent, int startId)  
	    {  
	    	
	    	String id=intent.getExtras().getString("taskId");
			TaskBean task = DBManager.getInstance().getTask(id);
	    	
			showNotification(task);
			
		    try{
				action.doTaskType(task);
			}catch (Exception e){
				Log.w("Error", e.getMessage());
			}
		    
		    this.onDestroy();
	    }

		@Override
		public IBinder onBind(Intent intent) {
			// TODO Auto-generated method stub
			return null;
		}  
		
		
		private void showNotification(TaskBean task){
			
			mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	    	Intent main = new Intent(this, MainActivity.class);   
	    	PendingIntent pIntent = PendingIntent.getActivity(this, 0, main, 0); 
	    	
	    	String msg = task.getName()+" 已于 "+task.getTime()+" 执行";
	    	String str="开启";
	    	if(task.getState().equals("N")) str="关闭";
	    	String msg2 = task.getTask()+str;
	    	
	    	NotificationCompat.Builder noti = new NotificationCompat.Builder(this)
	         .setContentTitle("自动任务执行通知")
	         .setContentText(msg)
	         .setSmallIcon(R.drawable.ic_launcher)
	         .setContentIntent(pIntent)
	         .setAutoCancel(true)
	         .setWhen(System.currentTimeMillis())
	    	 .setContentInfo(msg2);
	    	
	    	mNM.notify(1, noti.build());
		}
}
